package com.yiwei.zxp.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.zxp.Application;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.ComboBindCardBean;
import com.yiwei.zxp.api.bean.ComboCreditBean;
import com.yiwei.zxp.api.bean.OrderDetailBean;
import com.yiwei.zxp.api.model.OrderDetailModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.util.Arith;
import com.yiwei.zxp.util.DateTime;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.PreferenceUtils;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.PacketPayStepDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class MyOrderDetailActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_status_one)
    TextView txtStatusOne;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_card_type)
    TextView txtCardType;
    @BindView(R.id.img_card_type)
    ImageView imgCardType;
    @BindView(R.id.fl_card_type)
    FrameLayout flCardType;
    @BindView(R.id.txt_order_title)
    TextView txtOrderTitle;
    @BindView(R.id.txt_content)
    TextView txtContent;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_num)
    TextView txtNum;
    @BindView(R.id.txt_info_left)
    TextView txtInfoLeft;
    @BindView(R.id.txt_info_right)
    TextView txtInfoRight;
    @BindView(R.id.txt_info_two_left)
    TextView txtInfoTwoLeft;
    @BindView(R.id.txt_info_two_right)
    TextView txtInfoTwoRight;

    @BindView(R.id.btn_three)
    SuperButton btnThree;
    @BindView(R.id.btn_one)
    SuperButton btnOne;
    @BindView(R.id.txt_bank_card)
    TextView txtBankCard;
    @BindView(R.id.img_uline)
    ImageView imgUline;
    @BindView(R.id.layout_uline)
    LinearLayout layoutUline;
    @BindView(R.id.btn_two)
    SuperButton btnTwo;
    private Unbinder unbiner;
    private int x26;
    //    private List<RechargeTermDetailModel.DatasBean> periodsData;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;
    private String selectWays;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
    private static final String ACCOUNT = "BAG";
    private String orderMoney;
    private String orderNo;
    private String order_number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    public void getComboCredit(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ComboCreditBean bean = new ComboCreditBean();
        bean.order_number = order_number;

        Api.api_service.getComboCredit(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas != null) {
                        layoutUline.setVisibility(View.VISIBLE);
                        if (!TextUtils.isEmpty(result.datas.bankcard_no)) {
                            setData(result.datas.bankcard_no);
                        }

                        Glide.with(this).load(result.datas.credit_img).asBitmap().into(imgUline);
                    }
                });
    }

    public void setData(String account) {
        StringBuilder str = new StringBuilder(account.replace(" ", ""));

        int i = str.length() / 4;
        int j = str.length() % 4;

        for (int x = (j == 0 ? i - 1 : i); x > 0; x--) {
            str = str.insert(x * 4, " ");
        }

        txtBankCard.setText(str);
    }

    public void getOrderDetail(String order_number) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
        OrderDetailBean bean = new OrderDetailBean();
        bean.order_number = order_number;
        Api.api_service.getOrderDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    private void setData(OrderDetailModel.DatasBean datas) {
        orderMoney = datas.money;
        orderNo = datas.order_number;


        Spanned infoLeft = Spans.with(this).font("套餐类型", x26, 0xff999999).
                font("\n展位数量", x26, 0xff999999).
                font("\n套餐数量", x26, 0xff999999).
                font("\n最多可领淘淘币", x26, 0xff999999).
                font("\n套餐总额", x26, 0xff333333).
                build();
        txtInfoLeft.setText(infoLeft);

        Spanned infoRight = Spans.with(this).font(datas.combo_name, x26, 0xff999999).
                font("\n" + datas.combo_num + "个", x26, 0xff999999).
                font("\n" + datas.buy_num + "个", x26, 0xff999999).
                font("\n" + datas.shared_gold + "个", x26, 0xff999999).
                font("\n￥" + datas.money, x26, 0xffFB5E01).
                build();
        txtInfoRight.setText(infoRight);
        if (datas.pay_status.equals("0") || datas.pay_status.equals("2")) {
            Spanned infoTwoLeft = Spans.with(this).font("订单编号", x26, 0xff999999).
                    font("\n下单时间", x26, 0xff999999).
                    build();
            txtInfoTwoLeft.setText(infoTwoLeft);
            Spanned infoTwoRight = Spans.with(this).font(datas.order_number, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(datas.created_at * 1000), x26, 0xff999999).
                    build();
            txtInfoTwoRight.setText(infoTwoRight);


        } else if (datas.pay_status.equals("1")) {
            Spanned infoTwoLeft = Spans.with(this).font("订单编号", x26, 0xff999999).
                    font("\n下单时间", x26, 0xff999999).
                    font("\n支付方式", x26, 0xff999999).
                    font("\n支付时间", x26, 0xff999999).
                    build();
            txtInfoTwoLeft.setText(infoTwoLeft);
            //支付方式（1：线下支付，2：银行卡支付）
            String payWay="";
            if(datas.pay_way.equals("1")){
                payWay="线下支付";
            }else if(datas.pay_way.equals("2")){
                payWay="银行卡支付";
            }
            Spanned infoTwoRight = Spans.with(this).font(datas.order_number, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(datas.created_at * 1000), x26, 0xff999999).
                    font("\n" + payWay, x26, 0xff999999).
                    font("\n" + DateTime.toDateTime(datas.pay_date * 1000), x26, 0xff999999).
                    build();
            txtInfoTwoRight.setText(infoTwoRight);
        }

        txtOrderTitle.setText(datas.combo_name);
        txtContent.setText(datas.combo_num + "个商品展示位");
        txtMoney.setText("￥" + Arith.mul(Double.valueOf(datas.combo_single_money), Double.valueOf(datas.combo_num)));
        txtNum.setText("x" + datas.buy_num);
        if (datas.status.equals("0")) {
            String restTime = Util.getRestTime(datas.valid_date * 1000 - new Date().getTime());
            Spanned rest_time = Spans.with(this).font("等待买家付款\n", getResources().getDimensionPixelSize(R.dimen.x32), 0xffffffff).
                    font("剩" + restTime + "自动关闭", getResources().getDimensionPixelSize(R.dimen.x24), 0xffffffff).style(Typeface.BOLD).
                    build();
            txtStatusOne.setText(rest_time);

        } else {
            if (datas.pay_way.equals("1")) {
                txtStatusOne.setText(getStatus(datas.status) + "(线下支付)");
                getComboCredit(order_number);
            } else if (datas.pay_way.equals("2")) {
                txtStatusOne.setText(getStatus(datas.status) + "(银行卡支付)");
            } else {
                txtStatusOne.setText(getStatus(datas.status));
            }

        }


        Glide.with(this).load(datas.combo_image).into(imgCardType);

        //订单状态：-2：付款金额不满足，0 -待支付，1 - 已支付，2-支付失败、3-放弃购买，4：审核中，5：审核失败，6：待评价，7：已完成
        if (datas.status.equals("0")) {

            if (datas.pay_way.equals("1")) {
//            线下支付
                btnOne.setVisibility(View.VISIBLE);
                btnTwo.setVisibility(View.VISIBLE);
                btnTwo.setText("支付流程");
                btnThree.setVisibility(View.VISIBLE);
                btnThree.setText("完成支付");
            } else if (datas.pay_way.equals("2")) {
//银行卡支付
                btnOne.setVisibility(View.GONE);
                btnTwo.setVisibility(View.GONE);
                btnThree.setVisibility(View.VISIBLE);
                btnThree.setText("付款");
            }

            imgStatus.setImageResource(R.mipmap.img_status_need_pay);
        } else if (datas.status.equals("3")) {
            btnOne.setVisibility(View.GONE);
            btnTwo.setVisibility(View.VISIBLE);
            btnTwo.setText("删除订单");
            btnThree.setVisibility(View.VISIBLE);
            btnThree.setText("重新购买");
            imgStatus.setImageResource(R.mipmap.img_status_close);
        } else if (datas.status.equals("7") || datas.status.equals("1")) {
            btnOne.setVisibility(View.GONE);
            btnTwo.setVisibility(View.VISIBLE);
            btnTwo.setText("删除订单");
            btnThree.setVisibility(View.VISIBLE);
            btnThree.setText("再次购买");
            imgStatus.setImageResource(R.mipmap.img_status_goods_finish);
            if (datas.status.equals("7")) {
                txtStatusOne.setText("交易成功");
            }
        } else if (datas.status.equals("4")) {
            if (datas.pay_way.equals("1")) {
                btnOne.setVisibility(View.VISIBLE);
                btnTwo.setVisibility(View.GONE);
                btnThree.setVisibility(View.VISIBLE);
                btnThree.setText("修改凭证");
                Spanned shenheText = Spans.with(this).font("平台正在审核中", getResources().getDimensionPixelSize(R.dimen.x32), 0xffFFFFFF).
                        font("\n请耐心等待", getResources().getDimensionPixelSize(R.dimen.x24), 0xffFFFFFF).
                        build();
                txtStatusOne.setText(shenheText);
            }
        } else if (datas.status.equals("5")) {
            if (datas.pay_way.equals("1")) {
                btnOne.setVisibility(View.VISIBLE);
                btnTwo.setVisibility(View.GONE);
                btnThree.setVisibility(View.VISIBLE);
                btnThree.setText("重新购买");
                Spanned shenheText = Spans.with(this).font("抱歉，审核失败", getResources().getDimensionPixelSize(R.dimen.x32), 0xffFFFFFF).
                        font("\n原因是转账凭证不对", getResources().getDimensionPixelSize(R.dimen.x24), 0xffFFFFFF).
                        build();
                txtStatusOne.setText(shenheText);
            }
            imgStatus.setImageResource(R.mipmap.img_order_fail_icon);
        } else {
            btnOne.setVisibility(View.GONE);
            btnTwo.setVisibility(View.GONE);
            btnThree.setVisibility(View.GONE);
            imgStatus.setImageResource(R.mipmap.img_status_close);
        }

    }

    @OnClick({R.id.btn_one, R.id.btn_two, R.id.btn_three})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_one:
                Util.startActivity(this, WechatChatActivity.class);

                break;

            case R.id.btn_two:
                if (UI.toString(btnTwo).equals("支付流程")) {
                    new PacketPayStepDilaog(this).setOnChooseListener(new PacketPayStepDilaog.OnChooseListener() {
                        @Override
                        public void onSubmit() {

                        }
                    }).show();
                } else if (UI.toString(btnTwo).equals("删除订单")) {
                    Dialog.showDefaultDialog(this, "", "是否确定删除该订单？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getOrderDelete(orderNo);
                        }

                        @Override
                        public void cancel() {

                        }
                    });

                }
                break;
            case R.id.btn_three:

                if (UI.toString(btnThree).equals("完成支付")) {
//                    new PacketPayFinishDilaog(this).setOnChooseListener(new PacketPayFinishDilaog.OnChooseListener() {
//                        @Override
//                        public void onEditFinish(String count) {
//                            getBindBank(orderNo, count);
//                        }
//                    }).show();
                    Intent intent = new Intent(this, UlinePayFinishActivity.class);
                    intent.putExtra("order_number", orderNo);
                    intent.putExtra("is_has_upload", false);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                } else if (UI.toString(btnThree).equals("修改凭证")) {
                    Intent intent = new Intent(this, UlinePayFinishActivity.class);
                    intent.putExtra("order_number", orderNo);
                    intent.putExtra("is_has_upload", true);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                } else if (UI.toString(btnThree).equals("再次购买") || UI.toString(btnThree).equals("重新购买")) {
                    Util.startActivity(this, BoothPacketActivity.class);
                    finish();
                } else if (UI.toString(btnThree).equals("付款")) {
                    ArrayList<String> orderData = new ArrayList<String>();
                    orderData.add(order_number);
                    Intent intent = new Intent(this, BankPayMoneyActivity.class);
                    intent.putExtra("need_money", Double.valueOf(orderMoney));
                    intent.putStringArrayListExtra("data", orderData);
                    intent.putExtra("pay_type", Const.PayType.BOOTH_ORDER);
                    startActivity(intent);
                    finish();
                }

                break;
        }
    }

    //0 -待支付，1 - 已支付，2-支付失败、3-放弃购买，4：代发货，5：待收货，6：待评价，7：已完成
    private String getStatus(String status) {
        switch (status) {
            case "0":
                return "待付款";
            case "1":
                return "已支付";
            case "2":
                return "支付失败";
            case "3":
                return "订单失效";
            case "4":
                return "审核中";
            case "5":
                return "审核失败";
            case "6":
                return "";
            case "7":
                return "已完成";
            default:
                return "";
        }
    }

    private void init() {
        x26 = getResources().getDimensionPixelSize(R.dimen.x26);
        txtTitle.setText("展位订单详情");
        order_number = getIntent().getStringExtra("order_number");
        boolean is_uline = getIntent().getBooleanExtra("is_uline", false);
        if (is_uline) {
            getComboCredit(order_number);
        }
        getOrderDetail(order_number);
        initPay();
        mHandler = new PayHandler(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbiner.unbind();
        unbiner = null;
    }


    public void getOrderDelete(String order_num) {
        //    "全部", "待付款", "已付款"
        //状态（0：过期，1:有效，2：已使用)
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        OrderDetailBean bean = new OrderDetailBean();
        bean.order_number = order_num;
        Api.api_service.getOrderDelete(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "删除成功");

                    finish();
                });
    }

    public void getBindBank(String order_num, String bank_num) {
        //    "全部", "待付款", "已付款"
        //状态（0：过期，1:有效，2：已使用)
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        ComboBindCardBean bean = new ComboBindCardBean();
        bean.bankcard_no = bank_num;
        bean.order_number = order_num;
        Api.api_service.getComboBindCard(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "完成支付");
                    finish();
                });
    }

    //    ===========================获取支付方式===========================
    public void getPaymentList(double money, String bill_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
//        Api.api_service.getPaymentList().compose(RxLifeUtil.checkOn(this)).
//                doFinally(() -> {
//                    try {
//                        loadingDialog.dismiss();
//                    } catch (NullPointerException e) {
//
//                    }
//                }).
//                subscribe(result -> {
//                    Dialog.showRechargeTypeDialog(this, result.datas, new Dialog.DialogPaymentClickListener() {
//                        @Override
//                        public void confirm(String name, String id) {
//                            selectWays = name;
//                            if (selectWays.equals(ACCOUNT)) {
//                                getBagPayment(bill_no);
//                            } else {
//                                goToPay("支付", money, bill_no);
//                            }
//                        }
//
//                    });
//                });
    }
//    ===========================获取支付方式===========================

    //    ===========================余额支付===========================
    public void getBagPayment(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        loadingDialog.show();
//        PaymentBean bean = new PaymentBean();
//        bean.order_no = order_no;
//        Api.api_service.getBagPayment(bean).compose(RxLifeUtil.checkOn(this)).
//                doFinally(() -> {
//                    try {
//                        loadingDialog.dismiss();
//                    } catch (NullPointerException e) {
//
//                    }
//                }).
//                subscribe(result -> {
//                    ToastUtil.makeText(this, "支付成功");
//                });
    }
    //    ===========================余额支付===========================


    private void initPay() {
        // 推荐在主Activity或application里的onCreate函数中初始化BeeCloud.
//        if (!Const.IS_DEBUG) {
//            BeeCloud.setSandbox(true);
//
////        测试Appid和secret
//            BeeCloud.setAppIdAndSecret("956fb30c-0579-4469-aa31-64140d64e61c",
//                    "e32e1f0d-d219-4c76-8585-13f953327123");
//        } else {
        BeeCloud.setSandbox(false);
        //     正式网Appid和secret
        BeeCloud.setAppIdAndSecret(Const.BeeCloud.APP_ID,
                Const.BeeCloud.APP_Secret);
//        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, Const.BeeCloud.WECHAT_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    public void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("action", PayOrderitem.optional.action);
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("disable_pay_channels", "credit_group");
        if (TextUtils.isEmpty(selectWays)) {
            selectWays = ALI_APP;
        }
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
//            BCPay.getInstance(PayTypeActivity.this).reqAliPaymentAsync(
//                    PayOrderitem.title,
//                    PayOrderitem.order_money * 100,
//                    PayOrderitem.notice_sn,
//                    mapOptional,
//                    bcCallback);
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    null,
                    bcCallback);
        } else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {

//                BCPay.getInstance(this).reqWXPaymentAsync(
//                        PayOrderitem.title,               //订单标题
//                        PayOrderitem.order_money * 100,  //金额
//                        PayOrderitem.notice_sn,  //订单流水号
//                        mapOptional,            //扩展参数(可以null)
//                        bcCallback);            //支付完成后回调入口
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        null,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }


    private static class PayHandler extends Handler {
        WeakReference<MyOrderDetailActivity> mActivityReference;

        PayHandler(MyOrderDetailActivity activity) {
            mActivityReference = new WeakReference<MyOrderDetailActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final MyOrderDetailActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);

            /*
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
            */
        }
    };
}
